<?php

/**
 * 
 */
class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract {

    private $_controller = array(
        'controller' => 'error',
        'action' => 'denied'
    );

    public function __construct() {
        $auth = Zend_Auth::getInstance();
        // Определяем роль пользователя.
        // Если не авторизирован - значит "гость"
        $role = ($auth->hasIdentity() && !empty($auth->getIdentity()->role)) ? $auth->getIdentity()->role : 'guest';
        $acl = new Zend_Acl();

        //roles
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'));

        //resources
        $acl->add(new Zend_Acl_Resource('users'));
        $acl->add(new Zend_Acl_Resource('index'));
        $acl->add(new Zend_Acl_Resource('food'));
        $acl->add(new Zend_Acl_Resource('question'));
        $acl->add(new Zend_Acl_Resource('media'));
        $acl->add(new Zend_Acl_Resource('live'));

        //permissions
        $acl->deny();
        $acl->allow('admin', null)
                ->deny('admin', 'users', array('login', 'registration'));

        //Guest rights
        $acl->allow('guest', 'users', array('login', 'registration', 'confirm'))
                ->allow('guest', 'index')
                ->allow('guest', 'food', array('parse', 'index'))
                ->allow('guest', 'media', array('pictures', 'index'))
                //->allow('user', 'question', array('add', 'view', 'index'))
                ->allow('guest', 'live', array('index'));
        ;

        //User rights
        $acl->allow('user', 'users', array('logout', 'view','edit','index'))
                ->deny('user', 'users', array('login', 'registration', 'confirm'));

        Zend_Registry::set('acl', $acl);
        Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
        Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($role);
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $auth = Zend_Auth::getInstance();
        $acl = Zend_Registry::get('acl');

        if ($auth->hasIdentity()) {
            $role = $auth->getIdentity()->role;
        } else {
            $role = 'guest';
        }

        if (!$acl->hasRole($role)) {
            $role = 'guest';
        }

        $controller = $request->controller;
        $action = $request->action;

        if (!$acl->has($controller)) {
            $controller = null;
        }

        if (!$acl->isAllowed($role, $controller, $action)) {
            $request->setControllerName($this->_controller['controller']);
            $request->setActionName($this->_controller['action']);
        }
    }

}

?>